<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>聊天室管理后台</title>
  <style>
    body {
      display: flex;
      margin: 0;
      font-family: Arial, sans-serif;
      background: #f5f5f5;
    }
    .sidebar {
      width: 220px;
      background: #2c3e50;
      color: #fff;
      padding-top: 20px;
      display: flex;
      flex-direction: column;
      height: 100vh;
    }
    .menu-item {
      padding: 15px 20px;
      cursor: pointer;
      border-left: 4px solid transparent;
    }
    .menu-item:hover,
    .menu-item.active {
      background-color: #34495e;
      border-left: 4px solid #409eff;
    }
    .main {
      flex: 1;
      padding: 30px;
      background: #fff;
      overflow-y: auto;
    }
    .section {
      display: none;
    }
    .section.active {
      display: block;
    }
    h2 {
      margin-bottom: 20px;
    }
    .search-box {
      margin-bottom: 20px;
    }
    .search-box input {
      padding: 8px 12px;
      width: 250px;
      border: 1px solid #ccc;
      border-radius: 20px;
      outline: none;
    }
    .search-box button {
      margin-left: 10px;
      padding: 8px 16px;
      border: none;
      border-radius: 20px;
      background: #409eff;
      color: white;
      cursor: pointer;
    }
    .search-box .reset-btn {
      background: #e74c3c;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      background: #fff;
    }
    th, td {
      padding: 12px 16px;
      border-bottom: 1px solid #eee;
    }
    th {
      background: #f0f0f0;
      text-align: left;
    }
    button.action-btn {
      padding: 6px 12px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      color: white;
    }
    button.delete-btn {
      background: #e74c3c;
    }
    button.delete-btn:hover {
      background: #ff6f61;
    }
    button.ban-btn {
      background: #e67e22;
    }
    button.ban-btn:hover {
      background: #f39c12;
    }
    button.unban-btn {
      background: #2ecc71;
    }
    button.unban-btn:hover {
      background: #27ae60;
    }
        .status-normal {
      color: green;
      font-weight: bold;
    }

    .status-banned {
      color: red;
      font-weight: bold;
    }

    .pagination {
      margin-top: 10px;
      text-align: center;
    }

    .page-btn {
      margin: 0 3px;
      padding: 5px 10px;
      border: none;
      background-color: #eee;
      cursor: pointer;
      border-radius: 4px;
    }

    .page-btn.active {
      background-color: #007bff;
      color: white;
    }


  </style>
</head>
<body>

  <!-- 侧边栏 -->
  <div class="sidebar">
    <div style="text-align: center; font-size: 20px; font-weight: bold; padding: 20px 10px; border-bottom: 1px solid #444;">
      管理后台
    </div>
    <div class="menu-item active" id="menu-users" onclick="switchSection('users')">用户管理</div>
    <div class="menu-item" id="menu-messages" onclick="switchSection('messages')">聊天记录</div>
  </div>
  

  <!-- 主体 -->
  <div class="main">
    <!-- 用户管理 -->
    <div class="section active" id="section-users">
      

      <h2>用户管理</h2>
      <div class="search-box">
        <input type="text" id="searchInputUsers" placeholder="搜索用户ID或用户名">
        <button onclick="search()">搜索</button>
        <button class="reset-btn" onclick="resetSearch('users')">重置</button>
      </div>
      <table id="userTable">
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    

    </div>

    <!-- 聊天记录管理 -->
    <div class="section" id="section-messages">
      <h2>聊天记录管理</h2>
      <div class="search-box">
        <input type="text" id="searchInputMessages" placeholder="搜索消息ID或发送者">
        <button onclick="search()">搜索</button>
        <button class="reset-btn" onclick="resetSearch('messages')">重置</button>
      </div>
      <table id="messageTable">
        <thead>
          <tr>
            <th>消息ID</th>
            <th>发送者</th>
            <th>内容</th>
            <th>时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>
    <div id="pagination" class="pagination"></div>

  </div>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    let users = [];
    let messages = [];
    let currentSection = 'users';
  
    let currentPage = 1;
    let pageSize = 10;
  
    function switchSection(section) {
      currentSection = section;
      document.querySelectorAll('.menu-item').forEach(el => el.classList.remove('active'));
      document.querySelector(`#menu-${section}`).classList.add('active');
      document.querySelectorAll('.section').forEach(sec => sec.classList.remove('active'));
      document.querySelector(`#section-${section}`).classList.add('active');
  
      // 从接口加载数据
      if (section === 'users') {
        loadUsers();
      } else {
        loadMessages();
      }
    }
  
    function loadUsers() {
      $.ajax({
        url: '/getAllUser',
        method: 'GET',
        success: function (data) {
          if (Array.isArray(data)) {
            users = data;
            search();
          } else {
            alert('用户数据格式错误');
          }
        },
        error: function () {
          alert('加载用户失败');
        }
      });
    }
  
    function loadMessages() {
      $.ajax({
        url: '/getAllMessage',
        method: 'GET',
        success: function (data) {
          if (Array.isArray(data)) {
            messages = data;
            search();
          } else {
            alert('消息数据格式错误');
          }
        },
        error: function () {
          alert('加载消息失败');
        }
      });
    }
  
    function renderUserTable(data) {
      const tbody = document.querySelector('#userTable tbody');
      tbody.innerHTML = '';
  
      const start = (currentPage - 1) * pageSize;
      const end = start + pageSize;
      const pageData = data.slice(start, end);
  
      pageData.forEach(user => {
        const statusText = user.status === 1 ? '正常' : '封禁';
        const statusClass = user.status === 1 ? 'status-normal' : 'status-banned';
        const nextStatus = user.status === 1 ? 0 : 1;
        const buttonClass = user.status === 1 ? 'ban-btn' : 'unban-btn';
        const buttonText = user.status === 1 ? '封禁' : '解封';
  
        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td>${user.userId}</td>
          <td>${user.username}</td>
          <td><span class="${statusClass}">${statusText}</span></td>
          <td><button class="action-btn ${buttonClass}" onclick="toggleUserStatus(${user.userId}, ${nextStatus})">${buttonText}</button></td>
        `;
        tbody.appendChild(tr);
      });
  
      renderPagination(data.length);
    }
  
    function renderMessageTable(data) {
      const tbody = document.querySelector('#messageTable tbody');
      tbody.innerHTML = '';
      const start = (currentPage - 1) * pageSize;
      const end = start + pageSize;
      const pageData = data.slice(start, end);
  
      pageData.forEach(message => {
        const sender = message.fromName ? message.fromName : `用户ID: ${message.fromId}`;
        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td>${message.messageId}</td>
          <td>${sender}</td>
          <td>${message.content}</td>
          <td>${message.postTime}</td>
          <td><button class="action-btn delete-btn" onclick="deleteMessage(${message.messageId})">删除</button></td>
        `;
        tbody.appendChild(tr);
      });
  
      renderPagination(data.length);
    }
  
    function search() {
      if (currentSection === 'users') {
        const query = document.getElementById('searchInputUsers').value.trim();
        const filtered = users.filter(u =>
          u.userId?.toString().includes(query) || u.username?.includes(query)
        );
  
        renderUserTable(filtered);
      } else {
        const query = document.getElementById('searchInputMessages').value.trim();
        const filtered = messages.filter(m =>
          m.messageId.toString().includes(query) || m.fromName.includes(query)
        );
        renderMessageTable(filtered);
      }
    }
  
    function resetSearch(type) {
      if (type === 'users') {
        document.getElementById('searchInputUsers').value = '';
      } else {
        document.getElementById('searchInputMessages').value = '';
      }
      search();
    }
  
    function deleteMessage(id) {
      if (!confirm('确定要删除这条消息吗？')) return;
  
      $.ajax({
        url: `deleteMessage/${id}`,
        method: 'DELETE',
        success: function (data) {
          if (data == 1) {
            messages = messages.filter(m => m.messageId !== id);
            alert('删除成功');
            search();
          } else {
            alert('删除失败');
          }
        },
        error: function () {
          alert('请求失败');
        }
      });
    }
  
    function toggleUserStatus(userId, newStatus) {
      const statusText = newStatus == 1 ? '正常' : '封禁';
      if (!confirm(`确定要将用户 ${userId} 状态修改为「${statusText}」吗？`)) return;
  
      $.ajax({
        url: `/updateStatus`,
        method: 'POST',
        data: { status: newStatus, userId: userId },
        success: function (data) {
          if (data == 1) {
            const user = users.find(u => u.userId === userId); // 这里也要用 userId
            if (user) user.status = newStatus;
            alert('用户状态更新成功');
            search();
          } else {
            alert('更新失败');
          }
        },
        error: function () {
          alert('服务器错误');
        }
      });
    }
  
    // 页面加载完成后初始化
    window.onload = () => {
      switchSection('users'); // 默认先加载用户管理页
    };
  
    // 分页
    function renderPagination(totalItems) {
      const pagination = document.getElementById('pagination');
      const totalPages = Math.ceil(totalItems / pageSize);
      if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
      }
  
      let html = '';
      for (let i = 1; i <= totalPages; i++) {
        html += `<button class="page-btn ${i === currentPage ? 'active' : ''}" onclick="goToPage(${i})">${i}</button>`;
      }
  
      pagination.innerHTML = html;
    }
  
    function goToPage(page) {
      currentPage = page;
      search();
    }
  </script>
  
  

</body>
</html>
